package com.sskj.lib.model.repository;


import android.arch.lifecycle.LiveData;
import android.content.Context;
import android.text.TextUtils;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.sskj.common.base.HttpData;
import com.sskj.common.util.SPUtil;
import com.sskj.lib.BaseHttpConfig;
import com.sskj.lib.Constans;
import com.sskj.lib.SPConfig;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.http.JsonCallBack;
import com.sskj.lib.model.room.UserDao;
import com.sskj.lib.model.room.UserDataBase;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import io.reactivex.schedulers.Schedulers;

import static com.sskj.lib.BaseHttpConfig.BASE_URL;

/**
 * Created by lv on 18-5-7.
 */
//@Singleton
public class UserRepository {


    public UserDao userDao;

    @Inject
    public UserRepository(@Named("UserDao") UserDao userDao) {
        this.userDao = userDao;
    }

    public UserRepository(Context context) {
        UserDataBase userDataBase = UserDataBase.getInstance(context);
        userDao = userDataBase.getUserDao();
    }

    public LiveData<List<UserData>> getAllUser() {
        return userDao.getAll();
    }

    public void updateUser() {
        if (TextUtils.isEmpty(SPUtil.get(SPConfig.ACCOUNT, ""))) {
            return;
        }
        OkGo.<HttpData<UserData>>get(BASE_URL + "/Home/Qbw/user_info")
                .execute(new JsonCallBack<HttpData<UserData>>() {
                    @Override
                    public void onSuccess(Response<HttpData<UserData>> response) {
                        HttpData<UserData> httpData = response.body();
                        if (httpData.getStatus() == BaseHttpConfig.OK) {
                            SPUtil.put(Constans.SP_REALNAME_STATUS, httpData.getData().getStatus());
                            SPUtil.put(Constans.SP_REALNAME_STATUS_HIGH, httpData.getData().getAuth_status());
                            httpData.getData().setId(1);
                            insert(httpData.getData());
                        }
                    }

                    @Override
                    public void onError(Response<HttpData<UserData>> response) {
                        super.onError(response);
                        System.out.println("1");
                    }
                });
    }


    public void insert(UserData user) {
        Schedulers.newThread().scheduleDirect(() -> userDao.insert(user));
    }

    public void clear() {
        Schedulers.newThread().scheduleDirect(() -> userDao.deleteAll());
    }

    public void update(UserData user) {
        Schedulers.newThread().scheduleDirect(() -> userDao.update(user));
    }

    public void update() {
        updateUser();
    }
}
